// pages/container/order-details/activity-payed/activity-payed.js
const app = getApp();
const tool = require('../../../../utils/util.js');
const server = require("../../../../utils/server.js");
const chat_BG = require("../../../../utils/bg-imgs.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageShow: false,
    orderInfo: {},
    isIPhoneX: app.globalData.isIPhoneX,
    payMethod: "weixin",
    chat_BG: chat_BG.chat_BG,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    const _this = this;
    app.getLoadData().then(function(res){
      _this.setData({
        userInfo: res.data
      })
      _this.loadPage(options);

    })
  },
  switchChange: function (e) {
    const _this = this;
    var isWalletPay = e.detail.value;
    if (_this.data.orderInfo.available_predeposit <= 0) {
      isWalletPay = false;
    }
    this.setData({
      isWalletPay: isWalletPay
    })
  },
  /**
   * 选择付款方式
   */
  choosePayMethod: function (e) {
    const _this = this;
    const payMethod = e.currentTarget.dataset.payMethod;
    if (payMethod !== _this.data.payMethod) {
      _this.setData({
        payMethod: payMethod
      });
    }
  },
  /**
   * 加载订单详情
   */
  loadPage: function(options) {
    const _this = this;
    const param = {
      all_no: options.all_no,
      order_label: options.order_label,
      member_id: _this.data.userInfo.member_id
    }
    server.postJSON("/index/order/order_info",param,function(res){
      if(res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      _this.setData({
        pageShow: true
      });
      const chartParam = {
        member_id: _this.data.userInfo.member_id,
        ser_id: res.data.data.ser_id,
        all_no: res.data.data.all_no,
        getMsgType: "order"
      }
      if(res.data.data.order_label == 4) {
        res.data.data.showTplName = 'custom_order'
        chartParam.order_sn = res.data.data.order_sn
        chartParam.all_no = res.data.data.all_no;
        // 计算已支付总价
        var payedMoney = 0;
        // 计算已经支付金额
        for (var i = 0; i < res.data.data.pay_log.length; i++) {
          payedMoney += (res.data.data.pay_log[i].pay_money * 100)
        }
        payedMoney = payedMoney / 100;
        res.data.data.payedMoney = payedMoney;
        // 获取待支付金额
        if (res.data.data.project == '预付款') {
          res.data.data.topayMoney = res.data.data.deposit
        } else {
          res.data.data.topayMoney = res.data.data.order_amount - payedMoney
        }
        // 判断是否展示退款按钮
        res.data.data.isShowRefundBtn = [0, 10].indexOf(res.data.data.order_state) <= 0 || payedMoney > 0 ? true: false
        // 获取定制时间
        res.data.data.attend_time = tool.formatDate(new Date(res.data.data.customized_time * 1000), 'yyyy年mm月dd日 hh:ii');
      } else {
        res.data.data.showTplName = 'activity_order'
        
        chartParam.order_id = res.data.data.goods_list[0].order_id
        res.data.data.item_num = 0;
        for (var i = 0; i < res.data.data.goods_list.length; i++) {
          res.data.data.item_num += res.data.data.goods_list[i].item_num;
          res.data.data.goods_list[i].start_time = tool.formatDate(new Date(res.data.data.goods_list[i].activity.ua_start_time * 1000), 'yyyy-mm-dd');
          res.data.data.goods_list[i].unit_price = res.data.data.goods_list[i].activity.ua_price + '元/人';
        }
      }
      _this.getMesList(chartParam);
      res.data.data.creat_time = tool.formatDate(new Date(res.data.data.add_time * 1000), 'yyyy-mm-dd hh:ii:ss');
      // 加载客服信息
      _this.getServerData({
        ser_id: res.data.data.ser_id
      }); 
      _this.setData({
        orderInfo: res.data.data
      });
    });
  },
  // 获取客服信息
  getServerData: function (options) {
    const _this = this;
    server.postJSON("/index/chat/ser_info", options, function (res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      _this.setData({
        serverData: res.data.data
      });
    })
  },
  // 显示聊天界面
  showChat: function () {
    this.chat.showModal()
  },
  _resetMsg: function () {
    const _this = this;
    const chartParam = {
      member_id: app.globalData.userInfo.member_id,
      ser_id: _this.data.serverData.ser_id,
      order_id: _this.data.orderInfo.order_id,
      getMsgType: "order"
    }
    _this.getMesList(chartParam);
  },
  getMesList: function (param) {
    const _this = this;
    server.postJSON("/index/chat/selectmsg", param, function (res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      // if (res.data.data.data && res.data.data.data.length > 0) {
      //   for (var i = 0; i < res.data.data.data.length; i++) {
      //     res.data.data.data[i].send_time = tool.formatDate(new Date(res.data.data.data[i].add_time * 1000), 'mm-dd')
      //   }
      // }
      _this.setData({
        msgData: res.data.data
      });
      var query = wx.createSelectorQuery().in(_this);
      query.select('#scroll-container').boundingClientRect(function (res) {

        setTimeout(function () {
          _this.setData({
            scrollTop: res.height
          });
        }, 400);
      }).exec()
    });
  },
  // 调起支付
  topay: function () {
    const _this = this;
    const orderInfo = _this.data.orderInfo;
    console.log(typeof orderInfo.order_label)
    if (orderInfo.order_label == 4) {
      // return
      if (_this.data.payMethod === 'duigong' || _this.data.payMethod === 'xianjin') {
        _this.toCorporate.show();
        return
      }
    }

    const param = {
      all_no: _this.data.orderInfo.all_no,
      order_label: _this.data.orderInfo.order_label,
      openid: _this.data.userInfo.openid
    }
    if (_this.data.isWalletPay) {
      param.is_wallet = 2;
      wx.showModal({
        title: '提示',
        content: '确定使用钱包支付',
        success: function (res) {
          if (res.confirm) {
            _this.applyToPay(param)
          } else {
            tool.warning('您取消了')
          }
        }
      })
    } else {
      param.is_wallet = 1;
      _this.applyToPay(param);
    }
  },
  applyToPay: function (param) {
    server.postJSON("/index/Wxpay/index", param, function (res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      if (res.data.data.order_state == 20 || res.data.data.judge == 1) {
        tool.success('支付成功');
        setTimeout(function () {
          wx.switchTab({
            url: '/pages/container/order-list/order-list',
          });
        }, 1000);
        return;
      }
      wx.requestPayment({
        timeStamp: res.data.data.timeStamp,
        nonceStr: res.data.data.nonceStr,
        package: res.data.data.package,
        signType: 'MD5',
        paySign: res.data.data.paySign,
        success: function (r) {
          console.log(r)
          if (r.errMsg == "requestPayment:ok") {
            wx.navigateTo({
              // url: '/pages/container/order-details/order-details?all_no=' + param.all_no + "&order_label=" + param.order_label
              url: '/pages/container/order-list/order-list'
            })
          }
        },
        fail: function (res) {
          tool.warning("支付失败");
        }
      })
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.chat = this.selectComponent("#chat");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})